//
//  LLComposePictureView.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/7/3.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

private let cellId = "cell"

class LLComposePictureView: UICollectionView {
    
    // 告知外界弹出相册
    var composePictureViewClosure:(()->())?
    
    // 保存image的数组
    var imageList:[UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 供外界调用的方法
    func addImages(image: UIImage){
        imageList.insert(image, atIndex: 0)
        // 如果count 大于9 删除最后一张图片
        if imageList.count > 9 {
            imageList.removeLast()
        }
        
        hidden = false
        
        // 记得刷新数据
        reloadData()
    }
    
    //设置视图
    func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        //首次进入将配图隐藏
        hidden = true
        
        //注册
        registerClass(LLComposerPictureViewCell.self, forCellWithReuseIdentifier: cellId)
        
        dataSource = self
        
        delegate = self
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        let itemMargin: CGFloat = 5
        let cellWH = (SCREENW - 20 - itemMargin*2)/3
       // 设置item
       layout.itemSize = CGSize(width: cellWH, height: cellWH)
       // 设置垂直和水平间距
       layout.minimumInteritemSpacing = itemMargin
       layout.minimumLineSpacing = itemMargin

    }
}

extension LLComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = imageList.count
        
        if count == 0 || count == 9{
            
            return count
        }else{
        
        return count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! LLComposerPictureViewCell
        
        if imageList.count == indexPath.item{
            
           cell.image = nil
        }else{
            
            cell.image = imageList[indexPath.item]
        }
        
        //实现闭包
        cell.deleteButtonClouse = {
            
            self.imageList.removeAtIndex(indexPath.item)
            
            if self.imageList.count == 0 {
                
                self.hidden = true
            }
            
            self.reloadData()
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        // 如果数组的count ==  indexPath.item 就是加号按钮
        if imageList.count ==  indexPath.item{
            
            composePictureViewClosure?()
        }
    }
    
}
class LLComposerPictureViewCell: UICollectionViewCell {
    
    //声明删除按钮闭包
    var deleteButtonClouse:(()->())?
    
    var image: UIImage?{
        
        didSet{
            
            if image == nil{
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                deleteBtn.hidden = true
                
            }else {
                // 正常显示
                bgImageView.image = image
                // 解决cell重用问题
                bgImageView.highlightedImage = nil
                
                deleteBtn.hidden = false
                
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    func setupUI(){
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteBtn)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
    }
    
    //图片右上角删除按钮 点击事件
    @objc private func deleteButtonClick(){
        
        deleteButtonClouse?()
    }
    
    //懒加载
    private lazy var bgImageView: UIImageView = UIImageView()
    
    //图片右上角删除按钮
    private lazy var deleteBtn: UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()

}